<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
        </div>
      </template>
      
      <!-- 当前用户信息 -->
      <el-card class="current-user-card" shadow="never">
        <template #header>
          <span>当前登录用户</span>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ userStore.userInfo.id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ userStore.userInfo.username || '-' }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ userStore.userInfo.nickname || '-' }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ userStore.userInfo.email || '-' }}</el-descriptions-item>
          <el-descriptions-item label="角色">
            <el-tag v-for="role in userStore.roles" :key="role" :type="getRoleType(role)" style="margin-right: 5px;">
              {{ getRoleName(role) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="权限数量">{{ userStore.permissions.length || 0 }} 个权限</el-descriptions-item>
        </el-descriptions>
        
        <!-- 权限详情 -->
        <div v-if="userStore.permissions.length > 0" style="margin-top: 15px;">
          <h4>权限详情：</h4>
          <el-tag 
            v-for="permission in userStore.permissions" 
            :key="permission" 
            size="small" 
            style="margin: 2px;"
            :type="getPermissionType(permission)"
          >
            {{ permission }}
          </el-tag>
        </div>
      </el-card>
      
      <!-- 用户列表 -->
      <div class="user-list-section">
        <div class="section-header">
          <h3>用户列表</h3>
          <el-button 
            v-if="userRegisterEnabled" 
            type="primary" 
            @click="handleAddUser"
          >
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
          <el-tag 
            v-else 
            type="danger" 
            size="small"
            style="margin-left: 10px;"
          >
            用户注册功能已禁用
          </el-tag>
        </div>
        
        <el-table :data="userList" style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="nickname" label="昵称" width="120" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="enabled" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.enabled ? 'success' : 'danger'">
                {{ scope.row.enabled ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template #default="scope">
              <el-button size="small" @click="handleEditUser(scope.row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="warning" @click="handleManageRoles(scope.row)">
                <el-icon><Avatar /></el-icon>
                角色管理
              </el-button>
              <el-button size="small" type="danger" @click="handleDeleteUser(scope.row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
                 </div>
       </div>
     </el-card>
     
     <!-- 编辑用户对话框 -->
     <el-dialog
       v-model="editDialogVisible"
       title="编辑用户"
       width="500px"
       :close-on-click-modal="false"
       @close="cancelEdit"
     >
       <el-form
         ref="editFormRef"
         :model="editForm"
         :rules="editFormRules"
         label-width="80px"
       >
         <el-form-item label="用户ID">
           <el-input v-model="editForm.id" disabled />
         </el-form-item>
         <el-form-item label="用户名" prop="username">
           <el-input v-model="editForm.username" placeholder="请输入用户名" />
         </el-form-item>
         <el-form-item label="昵称" prop="nickname">
           <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
         </el-form-item>
         <el-form-item label="邮箱" prop="email">
           <el-input v-model="editForm.email" placeholder="请输入邮箱" />
         </el-form-item>
         <el-form-item label="状态">
           <el-switch
             v-model="editForm.enabled"
             active-text="启用"
             inactive-text="禁用"
           />
         </el-form-item>
       </el-form>
       
       <template #footer>
         <span class="dialog-footer">
           <el-button @click="cancelEdit">取消</el-button>
           <el-button type="primary" @click="submitEditForm">确定</el-button>
         </span>
       </template>
     </el-dialog>
     
     <!-- 添加用户对话框 -->
     <el-dialog
       v-model="addDialogVisible"
       title="添加用户"
       width="500px"
       :close-on-click-modal="false"
       @close="cancelAdd"
     >
       <el-form
         ref="addFormRef"
         :model="addForm"
         :rules="addFormRules"
         label-width="80px"
       >
         <el-form-item label="用户名" prop="username">
           <el-input v-model="addForm.username" placeholder="请输入用户名" />
         </el-form-item>
         <el-form-item label="昵称" prop="nickname">
           <el-input v-model="addForm.nickname" placeholder="请输入昵称" />
         </el-form-item>
         <el-form-item label="邮箱" prop="email">
           <el-input v-model="addForm.email" placeholder="请输入邮箱" />
         </el-form-item>
         <el-form-item label="密码" prop="password">
           <el-input 
             v-model="addForm.password" 
             type="password" 
             placeholder="请输入密码" 
             show-password
           />
         </el-form-item>
         <el-form-item label="状态">
           <el-switch
             v-model="addForm.enabled"
             active-text="启用"
             inactive-text="禁用"
           />
         </el-form-item>
       </el-form>
       
       <template #footer>
         <span class="dialog-footer">
           <el-button @click="cancelAdd">取消</el-button>
           <el-button type="primary" @click="submitAddForm">确定</el-button>
         </span>
       </template>
     </el-dialog>
     
     <!-- 角色管理对话框 -->
     <el-dialog
       v-model="roleDialogVisible"
       :title="`管理用户角色 - ${currentUser?.username}`"
       width="600px"
       :close-on-click-modal="false"
       @close="cancelRoleEdit"
     >
       <div v-loading="roleLoading">
         <div class="role-section">
           <h4>当前角色</h4>
           <div class="current-roles">
             <el-tag 
               v-for="role in currentUserRoles" 
               :key="role.id" 
               :type="getRoleTypeByLevel(role.level)"
               style="margin: 5px;"
             >
               {{ role.name }} - {{ role.description }}
             </el-tag>
             <el-tag v-if="currentUserRoles.length === 0" type="info">未分配角色</el-tag>
           </div>
           
           <h4 style="margin-top: 20px;">可分配角色</h4>
           <el-checkbox-group v-model="selectedRoleIds">
             <div v-for="role in allRoles" :key="role.id" class="role-item">
               <el-checkbox :label="role.id" class="role-checkbox">
                 <div class="role-info">
                   <span class="role-name">{{ role.name }}</span>
                   <el-tag 
                     :type="getRoleTypeByLevel(role.level)" 
                     size="small" 
                     style="margin-left: 10px;"
                   >
                     {{ getLevelNameByLevel(role.level) }}
                   </el-tag>
                   <div class="role-desc">{{ role.description }}</div>
                 </div>
               </el-checkbox>
             </div>
           </el-checkbox-group>
         </div>
       </div>
       
       <template #footer>
         <span class="dialog-footer">
           <el-button @click="cancelRoleEdit">取消</el-button>
           <el-button type="primary" @click="submitRoleForm" :loading="roleSubmitLoading">
             保存角色
           </el-button>
         </span>
       </template>
     </el-dialog>
   </div>
 </template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  getUserList, 
  deleteUser, 
  updateUser, 
  createUser,
  getUserRoles,
  assignUserRoles
} from '@/api/user'
import { getAllRoles } from '@/api/role'
import { getConfigStatus } from '@/api/system'

const userStore = useUserStore()

// 表格数据
const userList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 配置状态
const userRegisterEnabled = ref(true)

// 编辑对话框相关
const editDialogVisible = ref(false)
const editForm = reactive({
  id: null,
  username: '',
  nickname: '',
  email: '',
  enabled: true
})
const editFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { max: 50, message: '昵称长度不能超过 50 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}
const editFormRef = ref()

// 添加对话框相关
const addDialogVisible = ref(false)
const addForm = reactive({
  username: '',
  nickname: '',
  email: '',
  password: '',
  enabled: true
})
const addFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { max: 50, message: '昵称长度不能超过 50 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}
const addFormRef = ref()

// 角色管理对话框相关
const roleDialogVisible = ref(false)
const currentUser = ref(null)
const currentUserRoles = ref([])
const allRoles = ref([])
const selectedRoleIds = ref([])
const roleLoading = ref(false)
const roleSubmitLoading = ref(false)

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const response = await getUserList({
      current: currentPage.value,
      size: pageSize.value
    })
    
    if (response.code === 200) {
      userList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 添加用户
const handleAddUser = () => {
  // 重置表单
  addForm.username = ''
  addForm.nickname = ''
  addForm.email = ''
  addForm.password = ''
  addForm.enabled = true
  
  // 显示对话框
  addDialogVisible.value = true
}

// 提交添加表单
const submitAddForm = async () => {
  try {
    await addFormRef.value.validate()
    
    const response = await createUser({
      username: addForm.username,
      nickname: addForm.nickname,
      email: addForm.email,
      password: addForm.password,
      enabled: addForm.enabled ? 1 : 0
    })
    
    if (response.code === 200) {
      ElMessage.success('创建成功')
      addDialogVisible.value = false
      await fetchUserList()
    } else {
      ElMessage.error(response.message || '创建失败')
    }
  } catch (error) {
    console.error('创建用户失败:', error)
    ElMessage.error('创建失败')
  }
}

// 取消添加
const cancelAdd = () => {
  addDialogVisible.value = false
  addFormRef.value?.resetFields()
}

// 编辑用户
const handleEditUser = (user) => {
  // 填充表单数据
  editForm.id = user.id
  editForm.username = user.username
  editForm.nickname = user.nickname
  editForm.email = user.email
  editForm.enabled = user.enabled === 1
  
  // 显示对话框
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()
    
    const response = await updateUser(editForm.id, {
      username: editForm.username,
      nickname: editForm.nickname,
      email: editForm.email,
      enabled: editForm.enabled ? 1 : 0
    })
    
    if (response.code === 200) {
      ElMessage.success('更新成功')
      editDialogVisible.value = false
      await fetchUserList()
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新用户失败:', error)
    ElMessage.error('更新失败')
  }
}

// 取消编辑
const cancelEdit = () => {
  editDialogVisible.value = false
  editFormRef.value?.resetFields()
}

// 删除用户
const handleDeleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.username} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteUser(user.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      await fetchUserList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserList()
}

// 获取角色类型
const getRoleType = (role) => {
  const roleTypes = {
    'ROLE_SUPER_ADMIN': 'danger',
    'ROLE_ADMIN': 'warning',
    'ROLE_USER': 'success',
    'ROLE_GUEST': 'info'
  }
  return roleTypes[role] || 'info'
}

// 获取角色名称
const getRoleName = (role) => {
  const roleNames = {
    'ROLE_SUPER_ADMIN': '系统管理员',
    'ROLE_ADMIN': '管理员',
    'ROLE_USER': '普通用户',
    'ROLE_GUEST': '游客'
  }
  return roleNames[role] || role
}

// 获取权限类型
const getPermissionType = (permission) => {
  if (permission.includes('system:')) return 'danger'
  if (permission.includes('user:') || permission.includes('role:') || permission.includes('permission:')) return 'warning'
  if (permission.includes('article:') || permission.includes('comment:')) return 'success'
  if (permission.includes('category:') || permission.includes('tag:')) return 'primary'
  if (permission.includes('album:') || permission.includes('photo:')) return 'info'
  return 'info'
}

// 获取角色类型（根据级别）
const getRoleTypeByLevel = (level) => {
  const levelTypes = {
    0: 'info',      // 游客
    1: 'success',   // 普通用户
    2: 'warning',   // 管理员
    3: 'danger'     // 系统管理员
  }
  return levelTypes[level] || 'info'
}

// 获取级别名称
const getLevelNameByLevel = (level) => {
  const levelNames = {
    0: '游客',
    1: '普通用户',
    2: '管理员', 
    3: '系统管理员'
  }
  return levelNames[level] || '未知级别'
}

// 角色管理相关方法
const handleManageRoles = async (user) => {
  currentUser.value = user
  roleDialogVisible.value = true
  roleLoading.value = true
  
  try {
    // 获取所有角色
    const rolesResponse = await getAllRoles()
    if (rolesResponse.code === 200) {
      allRoles.value = rolesResponse.data || []
    }
    
    // 获取用户当前角色
    const userRolesResponse = await getUserRoles(user.id)
    if (userRolesResponse.code === 200) {
      currentUserRoles.value = userRolesResponse.data || []
      selectedRoleIds.value = currentUserRoles.value.map(role => role.id)
    }
  } catch (error) {
    console.error('获取角色信息失败:', error)
    ElMessage.error('获取角色信息失败')
  } finally {
    roleLoading.value = false
  }
}

// 提交角色分配
const submitRoleForm = async () => {
  roleSubmitLoading.value = true
  
  try {
    const response = await assignUserRoles(currentUser.value.id, selectedRoleIds.value)
    
    if (response.code === 200) {
      ElMessage.success('角色分配成功')
      roleDialogVisible.value = false
      // 刷新用户列表
      await fetchUserList()
    } else {
      ElMessage.error(response.message || '角色分配失败')
    }
  } catch (error) {
    console.error('角色分配失败:', error)
    ElMessage.error('角色分配失败')
  } finally {
    roleSubmitLoading.value = false
  }
}

// 取消角色编辑
const cancelRoleEdit = () => {
  roleDialogVisible.value = false
  currentUser.value = null
  currentUserRoles.value = []
  allRoles.value = []
  selectedRoleIds.value = []
  roleLoading.value = false
  roleSubmitLoading.value = false
}

// 检查配置状态
const checkConfigStatus = async () => {
  try {
    const response = await getConfigStatus()
    if (response.code === 200) {
      userRegisterEnabled.value = response.data.userRegisterEnabled
    }
  } catch (error) {
    console.error('获取配置状态失败:', error)
    ElMessage.error('获取配置状态失败')
  }
}

onMounted(() => {
  fetchUserList()
  checkConfigStatus()
})
</script>

<style lang="scss" scoped>
.user-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.current-user-card {
  margin-bottom: 20px;
  
  :deep(.el-card__header) {
    background: #f8f9fa;
    font-weight: bold;
  }
}

.user-list-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h3 {
      margin: 0;
      color: #303133;
    }
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-container {
    padding: 10px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}

// 角色管理对话框样式
.role-section {
  h4 {
    margin: 15px 0 10px 0;
    color: #303133;
    font-weight: bold;
  }
  
  .current-roles {
    min-height: 40px;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
  }
  
  .role-item {
    margin: 10px 0;
    padding: 12px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    background: #fff;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: #409eff;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
    }
    
    .role-checkbox {
      width: 100%;
      
      :deep(.el-checkbox__label) {
        width: 100%;
        padding-left: 10px;
      }
    }
    
    .role-info {
      .role-name {
        font-weight: bold;
        color: #303133;
        font-size: 14px;
      }
      
      .role-desc {
        color: #606266;
        font-size: 12px;
        margin-top: 5px;
        line-height: 1.4;
      }
    }
  }
}
</style>
